<?php

namespace app\admin\controller;

use think\Controller;
use app\util\Util;
use app\admin\model\Admin;

/*
* 默认
*/
class IndexController extends Controller
{
    /*
    * 登录页面
    */
    public function index()
    {
        $adminData = session('adminData', '');
        if ($adminData != '') {
            header('Location:' . url('admin/main/index','',''));
            exit;
        }

        return view('index');
    }

    /*
    * 登录
    */
    public function login()
    {
        $all = input('post.');

        $username = $all['username'];
        $password = $all['password'];

        $admin = new Admin();

        $row = $admin->where('username', '=', $username)->find();
        if (is_null($row)) {
            return Util::ajaxReturn(0, '账号不存在', null);
        }

        $password = $row['salt'] . $password . $row['salt'];

        if ($row['password'] == md5($password)) {
            $adminData = [
                'id' => $row['id'],
                'username' => $row['username'],
            ];
            session('adminData', $adminData);

            return Util::ajaxReturn(1, '登录成功', null);
        } else {
            return Util::ajaxReturn(0, '密码错误', null);
        }
    }

    /*
    * 退出
    */
    public function logout()
    {
        session('adminData', null);

        header('Location:' . url('admin/index/index','',''));
        exit;
    }

}
